<template>
  <div class="customer-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-input
          placeholder="请输入护理级别"
          style="width: 200px"
          v-model="queryLevel"
          class="search-input"
      ></el-input>
      <el-button
          @click="queryLevelList"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
      <el-button
          @click="showLevelDialog"
          type="primary"
          class="register-button"
      >
        添加
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 护理级别表格 -->
    <el-table
        :data="levelList"
        class="customer-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="levelId"
          label="护理级别"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="levelStatus"
          label="状态"
          width="100px"
          align="center"
      >
        <template #default="scope">
          {{ scope.row.levelStatus === 1 ? '启用' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="340px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showEditDialog(scope.row.id)"
              class="edit-button"
          >
            修改
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="toggleLevelStatus(scope.row.id)"
              class="delete-button"
          >
            {{ scope.row.levelStatus === 1 ? '停用' : '启用' }}
          </el-button>
          <el-button
              type="success"
              size="small"
              @click="toContentConfig(scope.row.id, scope.row.levelName)"
              class="config-button"
          >
            护理内容配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 护理级别对话框 -->
    <el-dialog
        v-model="levelDialog"
        :title="dialogTitle"
        class="customer-dialog"
    >
      <el-form :model="curLevel" class="customer-form">
        <el-form-item label="护理级别" class="form-item">
          <el-col :span="22">
            <el-input v-model="curLevel.levelId" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="状态" class="form-item">
          <el-col :span="22">
            <el-select v-model="curLevel.levelStatus" class="form-select">
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="2"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="optLevel()" class="dialog-button">{{ buttonOpt }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive} from "vue";
import http from '@/axios/http.js';
import qs from "qs";
import {useRouter} from 'vue-router';

const router = useRouter(); // 此处获取实例，作用域覆盖整个组件

// 护理级别列表
let levelList = ref([]);
// 错误提示
let errorMessage = ref("");
// 搜索关键字
let queryLevel = ref("");
// 对话框显示控制
let levelDialog = ref(false);
// 当前编辑的护理级别
let curLevel = ref({});
// 对话框标题和按钮文字
let dialogTitle = reactive("");
let buttonOpt = reactive("");
// 操作类型：1添加，2编辑
let dialogOptType = reactive(1);
// 分页信息
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 获取护理级别列表
function queryLevelList() {
  let params = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    keyword: queryLevel.value
  };
  http.post('/lyy/listNurseLevel', qs.stringify(params)).then((res) => {
    let result = res.data;
    if (res.data.result === 'success') {
      pageContains.value = result.data;
      levelList.value = result.data.list;
    } else {
      errorMessage.value = result.error;
    }
  });
}

//// 显示添加对话框
function showLevelDialog() {
dialogTitle = "添加护理级别";
buttonOpt = "添加"; // 按钮文本应为“添加”
dialogOptType = 1; // 操作类型设为“添加”

curLevel.value = {
  levelId: '',
  levelStatus: '1', // 默认启用状态
  remark: ''
};
levelDialog.value = true;
}

// 显示编辑对话框
function showEditDialog(id) {
  dialogTitle = "修改护理级别";
  buttonOpt = "修改";
  dialogOptType = 2;

  http.post('/lyy/getNurseLevelById', qs.stringify({ id: id })).then((res) => { // 修正路径
    if (res.data.result === 'success') {
      // 新增严格的数据类型校验
      if (typeof res.data.data === 'object' && res.data.data !== null && !Array.isArray(res.data.data)) {
        curLevel.value = res.data.data;
        levelDialog.value = true;
      } else {
        console.error('数据格式异常，预期对象类型', res.data.data);
        errorMessage.value = '获取护理级别信息失败，请重试';
      }
    } else {
      errorMessage.value = res.data.error;
    }
  }).catch((error) => {
    console.error('网络请求异常', error);
    errorMessage.value = '网络请求失败，请检查网络连接';
  });
}
// 操作护理级别（添加/修改）
function optLevel() {
  let param = {
    id: curLevel.value.id,
    levelId: curLevel.value.levelId,
    levelStatus: curLevel.value.levelStatus,
    remark: curLevel.value.remark
  };
  if (dialogOptType === 1) {
    addNurseLevel(param);
  } else {
    updateNurseLevel(param);
  }
}

// 添加护理级别
function addNurseLevel(param) {
  http.post('/lyy/addNurseLevel', param).then((res) => {
    if (res.data.result === 'success') {
      levelDialog.value = false;
      queryLevelList();
    } else {
      errorMessage.value = res.data.error;
    }
  });
}

// 修改护理级别
function updateNurseLevel(param) {
  http.post('/lyy/updateNurseLevel', param).then((res) => {
    if (res.data.result === 'success') {
      levelDialog.value = false;
      queryLevelList();
    } else {
      errorMessage.value = res.data.error;
    }
  });
}

// 切换护理级别状态
function toggleLevelStatus(id) {
  http.post('/lyy/toggleNurseLevelStatus', qs.stringify({ id: id })).then((res) => {
    if (res.data.result === 'success') {
      // 更新列表中的状态
      const index = levelList.value.findIndex(item => item.id === id);
      if (index !== -1) {
        levelList.value[index].levelStatus = res.data.data.levelStatus;
      }
      queryLevelList();
    } else {
      errorMessage.value = res.data.error;
    }
  });
}

// 分页处理
const handlePageChange = (pageNum1) => {
  pageContains.value.pageNum = pageNum1;
  queryLevelList();
};

const handleSizeChange = (pageSize1) => {
  pageContains.value.pageSize = pageSize1;
  queryLevelList();
};

// 初始化
onMounted(() => {
  queryLevelList();
});

// // 跳转到护理项目管理页面（Nursetem.vue）
// function toContentConfig(levelId, levelName) {
//   const router = useRouter();
//   router.push({
//     url: 'nurse/nurseItem',
//     query: { levelId: levelId, levelId: levelId } // 按需传递参数
//   });
// }
// 初始化路由实例（在 setup 作用域内）


// 跳转到护理项目管理页面（直接使用顶层声明的 router）
function toContentConfig(levelId, levelName) {
  router.push({ // 直接使用已声明的 router 实例
    path: '/nurse/nurseItem', // 目标路由路径（需与 router/index.js 一致）
    query: { levelId, levelName } // 简化参数传递
  });
}
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.register-button {
  width: 100px;
  font-weight: bold;
  font-size: 16px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.customer-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.customer-dialog {
  width: 500px;
}

.customer-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input,
.form-select {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}

.edit-button {
  margin-right: 10px;
}

.delete-button {
  margin-right: 10px;
}

.config-button {
  margin-right: 10px;
}
</style>
